﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Net.Http.Headers;
using System.IO;
using System.Drawing;
using System.Text;

namespace Chat_WebServer.Controllers
{
    public class AvatarController : ApiController
    {
        // Lay avatar
        public HttpResponseMessage Get(string username)
        {
            var file = HttpContext.Current.Server.MapPath("~/") + "Avatar/" + username + ".jpg";
            var http = new WebClient();
            if(!File.Exists(file))
                file = HttpContext.Current.Server.MapPath("~/") + "Avatar/default.jpg";
            var imageData = http.DownloadData(file);
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(imageData);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            return result;
        }

        //Post api/Picture/username?ar
        public HttpStatusCode PostPicture(String id, [FromBody]byte[] picture)
        {         
            byte[] img = picture;

            if (null == img)
                return HttpStatusCode.BadRequest;
            try
            {
                //Create image
                String path = HttpContext.Current.Server.MapPath("~/") + "Avatar/" + id.Trim() + ".jpg";
                Image pic = byteArrayToImage(img);
                pic.Save(path);
            }
            catch (Exception ex)
            {
                return HttpStatusCode.BadRequest;
            }
            return HttpStatusCode.OK;
        }

        private static Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }
    }
}
